package com.ruoyi.web.controller.guarantee;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.guarantee.domain.BAgreement;
import com.ruoyi.guarantee.service.IBAgreementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.*;

@RestController
public class FileDownloadController {
    @Autowired
    private IBAgreementService bAgreementService;
    @RequestMapping(value = "/downloadFile/{id}", method = RequestMethod.GET)
    public void downloadZip(HttpServletResponse response,@PathVariable("id") Long id) throws IOException {

        BAgreement bAgreement = bAgreementService.selectBAgreementById(id);
        List<File> files = new ArrayList<>();
        if (StringUtils.isNotEmpty(bAgreement.getXmArticleUrl())){
            String[] xmArticlePaths = bAgreement.getXmArticleUrl().split(",");
            for (int i = 0;i<xmArticlePaths.length;i++){
                String xmArticlePath = xmArticlePaths[i].replace("/profile", RuoYiConfig.getProfile());
                File file = new File(xmArticlePath);
                if(file.exists()){
                    files.add(file);
                }
            }
        }

        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment;filename=" + "license-"+ bAgreement.getXmName()+".zip");
        try( ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());){
            for(File f:files){
                zipFile(f,f.getName(), zos);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public  void zipFile(File fileToZip, String fileName, ZipOutputStream zos) throws IOException {
        try ( FileInputStream fis = new FileInputStream(fileToZip);){
            ZipEntry zipEntry = new ZipEntry(fileName);
            zos.putNextEntry(zipEntry);

            byte[] bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) >= 0) {
                zos.write(bytes, 0, length);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
